package com.open.capacity.study.service.impl;

import com.open.capacity.common.exception.service.ServiceException;
import com.open.capacity.common.model.LearnProcess;
import com.open.capacity.common.model.Stage;
import com.open.capacity.common.util.PageUtil;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.study.dao.LearnProcessDao;
import com.open.capacity.study.dao.StageDao;
import com.open.capacity.study.service.LearnProcessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class LearnProcessServiceImpl implements LearnProcessService {
    @Autowired
    private LearnProcessDao learnProcessDao;
    @Autowired
    private StageDao stageDao;


    /**
     * 添加用户学习进度
     * @param learnProcess
     * @return
     * @throws ServiceException
     */
    @Override
    public Result insert(LearnProcess learnProcess) throws ServiceException {
        try {
            learnProcess.setCretim(new Date());
            learnProcess.setStatim(new Date());
            int res = learnProcessDao.insert(learnProcess);
            log.info("新增学习进度阶段：{}",learnProcess);
            return res > 0 ? Result.succeed(learnProcess,"新增成功"):Result.failed("新增失败");
        }catch (Exception e){
            throw new ServiceException(e);
        }
    }

    /**
     * 评价和评分
     * @return
     * @throws ServiceException
     */
    @Override
    public Result updateScore(LearnProcess learnProcess) throws ServiceException {
        try{
            String userid = learnProcess.getUserid();
            String stcode = learnProcess.getStcode();
            String score = learnProcess.getScore();
            //评分(方式不齐全)
            if ( score != null&&!score.equals("") ){
                //判断历史分数是否大于等于60
                Map<String,Object> map = new HashMap<>();
                map.put("lepcid",learnProcess.getLepcid());
                List<LearnProcess> list = learnProcessDao.findList(map);
                LearnProcess learnProcess1 = list.get(0);
                if (Integer.parseInt(learnProcess1.getScore())>=60 ){       //当前阶段的分数大于60，代表通过，不能修改
                    return Result.failed("不能修改分数！");
                }
                //首次通过添加分数、重修的修改分数
                if (Integer.parseInt(score) >= 60 ){                         //分数大于60时，通过，进入下阶段
                    if (Integer.parseInt(learnProcess1.getScore())==-1){    //首次打分，标记首次通过
                        learnProcess.setIsfirst(1);
                    }
                    learnProcess.setEndtim(new Date());
                    learnProcess.setStatus(1);
                    learnProcessDao.update(learnProcess);
                    log.info("学习进度阶段评分：{}",learnProcess);
                    //添加新用户学习阶段进度
                    stcode = NextStage(stcode);
                    if (stcode != "") {
                        LearnProcess learn = new LearnProcess();
                        learn.setUserid(userid);
                        learn.setStcode(stcode);
                        return insert(learn);
                    }else {
                        //修改状态为毕业
                        learnProcessDao.graduate(userid);
                        return Result.succeed("已经是最后一个阶段了");
                    }
                }else {                                                     //分数小于60
                    learnProcess.setIsfirst(2);                             //标记非首次通过
                    learnProcessDao.update(learnProcess);
                    log.info("学习进度阶段评分：{}",learnProcess);
                    return Result.succeed("未通过！");
                }
            }
            return null;
        }catch (Exception e){
            throw new ServiceException(e);
        }
    }

    /**
     * 修改学习总结
     * @param learnProcess
     * @return
     * @throws ServiceException
     */
    @Override
    public Result updateSummary(LearnProcess learnProcess) throws ServiceException {
        try {
            String summary = learnProcess.getSummar();
            if (summary != null && !summary.equals("") ){
                int res = learnProcessDao.update(learnProcess);
                log.info("修改学习总结",learnProcess);
                return res>0 ?Result.succeed(learnProcess,"修改成功"):Result.failed("修改失败");
            }
            return null;
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 条件查询
     * 条件：用户id集合，阶段
     * @param params
     * @return
     * @throws ServiceException
     */
    @Override
    public PageResult<LearnProcess> findList(Map<String, Object> params) throws ServiceException{
        try {
            int count = learnProcessDao.count(params);
            PageUtil.pageParamConver(params,false);
            List<LearnProcess> list = Collections.emptyList();
            list = learnProcessDao.findList(params);
            //计算天数
            for (int i=0;i<list.size();i++){
                LearnProcess lp = getDays(list.get(i));
                list.set(i,lp);
            }
            return PageResult.<LearnProcess>builder().data(list).code(0).count((long)count).build();
        }catch (Exception e){
            throw new ServiceException(e);
        }
    }

    /**
     * 其他查询
     * @param params
     * @return
     * @throws ServiceException
     */
    @Override
    public Result otherQuery(Map<String, Object> params) throws ServiceException {
        try {
            Map<String,Object> map = new HashMap<>();
            //每个阶段人数
            List<LearnProcess> countPeople = learnProcessDao.countPeople();
            map.put("countPeople",countPeople);
            //每个阶段停留平均天数
            List<LearnProcess> avgDays = learnProcessDao.avgDays();
            map.put("avgDays",avgDays);
            //通过人数
            List<LearnProcess> passNum = learnProcessDao.passNum();
            map.put("passNum",passNum);
            return Result.succeedWith(map,0,"");
        }catch (Exception e){
            throw new ServiceException(e);
        }
    }

    /**
     * 计算天数
     * @param learnProcess
     */
    private LearnProcess getDays(LearnProcess learnProcess) {
        Date endtim = learnProcess.getEndtim();
        Date statim = learnProcess.getStatim();
        if (endtim==null){
            endtim = new Date();
        }
        int days = (int) ((endtim.getTime() - statim.getTime())/(1000*3600*24));
        learnProcess.setDays(days);
        return learnProcess;
    }

    /**
     * 获得下一阶段的code
     * @param stcode
     * @return
     */
    private String NextStage(String stcode) {
        //查询当前阶段的排序
        Stage byCode = stageDao.findByCode(stcode);
        float sorder = byCode.getSorder();
        int total = stageDao.count(byCode.getTsysId());
        //查询下一阶段的code
        if (sorder>=total){                             //当前排序值sorder 和此体系总阶段数比较
            return "";
        }else {
            Map<String,Object> map = new HashMap<>();
            map.put("tsysId",byCode.getTsysId());
            map.put("sorder",sorder+1);
            List<Stage> list = stageDao.findList(map);
            Stage stage = list.get(0);
            return stage.getStcode();
        }
    }

}
